//
//  CustomerDetailVC.swift
//  Employee
//
//  Created by tancheng on 2018/7/23.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import Foundation
import SwiftyJSON

class CustomerDetailVC: BaseVC {
    
    @IBOutlet weak var scroll: UIScrollView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var maritalStatus: UILabel! //婚姻状况
    @IBOutlet weak var education: UILabel! // 学历
    @IBOutlet weak var nation: UILabel!// 民族
    @IBOutlet weak var mobile: UILabel!
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var remark: UILabel!
    @IBOutlet weak var emergencyContact: UILabel!
    
    @IBAction func callOwnerPhone(_ sender: UIButton) {
        call(model.phone)
    }
   
    @IBAction func callEmergencyContactPhone(_ sender: UIButton) {
        call(model.sosPhone)
    }
    
    @IBOutlet weak var infoViewHeight: NSLayoutConstraint! //357
    //
    @IBOutlet weak var tagBgView: UIView!
    @IBOutlet weak var lableHeight: NSLayoutConstraint!//标签,160
    
    @IBOutlet weak var houseBgView: UIView!
    @IBOutlet weak var houseViewHeight: NSLayoutConstraint!//房产
    
    @IBOutlet weak var carSiteBgView: UIView!
    @IBOutlet weak var stallViewHight: NSLayoutConstraint!//车位
    
    @IBOutlet weak var carView: UIView!
    @IBOutlet weak var carViewHeight: NSLayoutConstraint!//车辆
    
    @IBOutlet weak var editBtn: UIButton!
    @IBAction func editTag(_ sender: UIButton) {
        let vc = CustomerTagVC()
        vc.pastTags = model.tags
        vc.customerId = model.id
        vc.updateClosure = { [weak self] selData in
            self?.model.tags = selData
            self?.congigureTag(selData)
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    
    func call(_ phone: String) {
        if phone.isEmpty {
            return
        }
        let url = URL(string: "tel:" + phone)
        let web = UIWebView()
        web.loadRequest(URLRequest(url: url!))
        SJApp.keyWindow.addSubview(web)
    }
    
    var model: CustomerDetailModel!
    var id:String!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scroll.delegate = self
        if !User.permission_customer_view && !User.systemAdmin {//判断权限
            editBtn.isHidden = true
        }
        
        getDetail()
    }
    
    
    func getDetail() {
        
        scroll.isHidden = true
        SJApp.showHUD(in: view)
        var send = CustomerDetailSend()
        send.id = id
       let _ = CustomerRequest.shared.getCustomerDetail(send: send, success: { (deModel) in
        SJApp.hideHUD(in: self.view)
            self.model = deModel
            self.scroll.isHidden = false
            self.configureData()
        
        }) {
            SJApp.hideHUD(in: self.view)
        }
        
    }
    
    
    func configureData() {
        
        //title = model.name + "的信息"
        
        name.text = model.name
        nation.text = model.nationName
        education.text = getDiplomaText(model.diploma)
        maritalStatus.text = getMaritalStatusText(model.maritalStatus)
        mobile.text = model.phone
        address.text = model.regResidence.isEmpty ? "无" : model.regResidence
        remark.text = model.remark.isEmpty ? "无" : model.remark
        emergencyContact.text = model.sosName + " " + model.sosPhone
        if emergencyContact.text!.trim().isEmpty {
            emergencyContact.text = "无"
        }
        
        
       let remarkHeight = UIFont.calculateHeight(width: view.bounds.width-40, font: GlobalConfig.system16Font, text: remark.text!)
        
        infoViewHeight.constant = 357 - 30 + remarkHeight
        
        
        
        ///
        congigureTag(model.tags)
        
        congigureRelevanceHouse()
        congigureRelevanceCarSite()
        congigureRelevanceCar()
    }
    
    func getNoLab(title: String) -> UILabel {
        let lab = UILabel()
        lab.text = title
        lab.textColor = GlobalConfig.TextDeepColor.withAlphaComponent(0.5)
        lab.font = GlobalConfig.system16Font
        lab.textAlignment = .center
        return lab
    }
    
    func congigureTag(_ tagData: [TagModel]) {
        
        var y: CGFloat = 60
        var x: CGFloat = 20
        
       
        for view in tagBgView.subviews {//清理数据
            if view.tag != 999 && view.tag != 998 {
                view.removeFromSuperview()
            }
        }
        
        
        if tagData.count == 0 {
            //
            let nolab = getNoLab(title: "TA还没有标签")
            tagBgView.addSubview(nolab)
            nolab.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
            })
            
            return
        }
        
        for tag in tagData {
            let tagName = tag.name
            let itemWidth = tagWidth(tagName)

            if x + itemWidth > UIScreen.width - 20 - 20 {
                x = 20
                y += 20 + 10
            }
            
            let item = TagItem(frame: CGRectMake(x, y, itemWidth, 20), title: tagName)
            tagBgView.addSubview(item)
            x += itemWidth + 10
        }
        
        
        
        if y + 10 > 160 {
            lableHeight.constant = y+10
        }
        
        
    }
    
    private func tagWidth(_ tagName: String) -> CGFloat {
       return UIFont.calculateWidth(font: GlobalConfig.system14Font, text: tagName) + 20
    }
    
    func congigureRelevanceHouse() {
        var y: CGFloat = 60
        
        if model.houses.count == 0 {
            //
            let nolab = getNoLab(title: "TA还没有关联的房产")
            houseBgView.addSubview(nolab)
            nolab.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
            })
            return
        }
        
        
        for house in model.houses  {
            let item = CustomerRelevanceItem(frame: CGRectMake(0, y, view.bounds.width-20, 22), data: [house.numberDesc,getCunstomerTypeDesc(house.customerType),""])
            houseBgView.addSubview(item)
            y += 22 + 10
        }
        
        if y + 10 > 160 {
            houseViewHeight.constant = y+10
        }
        
    }
    
    func congigureRelevanceCarSite() {
        
        
        if model.carSites.count == 0 {
            //
            let nolab = getNoLab(title: "TA还没有关联车位")
            carSiteBgView.addSubview(nolab)
            nolab.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
            })
            return
        }
        
        var y: CGFloat = 60
        for site in model.carSites {
            let item = CustomerRelevanceItem(frame: CGRectMake(0, y, view.bounds.width-20, 22), data: [site.numberDesc,getCunstomerTypeDesc(site.customerType),site.carNumber])
            carSiteBgView.addSubview(item)
            y += 22 + 10
        }
        
        if y + 10 > 160 {
            stallViewHight.constant = y+10
        }
        
    }
    
    func congigureRelevanceCar() {
       
        if model.cars.count == 0 {
            //
            let nolab = getNoLab(title: "TA还没有关联车辆")
            carView.addSubview(nolab)
            nolab.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
            })
            return
        }
        
        var y: CGFloat = 60
        for car in model.cars {
            let item = CustomerRelevanceItem(frame: CGRectMake(0, y, view.bounds.width-20, 22), data: [car.carNumber,car.carAreaName,getCardText(car.cardType)])
            carView.addSubview(item)
            y += 22 + 10
        }
        
        if y + 10 > 160 {
            carViewHeight.constant = y+10
        }
        
    }
    
    //
    func getMaritalStatusText(_ type: String) -> String {
        
        switch type {
        case "UNMARRIED":
            return "未婚"
        case "MARRIED":
            return "已婚"
        case "WIDOWED":
            return "丧偶"
        case "DIVORCE":
            return "离婚"
        default:
            return ""
        }
        
        
    }
    
    func getDiplomaText(_ type: String) -> String {
        
        switch type {
        case "WenMang":
            return "文盲"
        case "BanWenMang":
            return "半文盲"
        case "PrimarySchool":
            return "小学"
        case "MiddleSchool":
            return "初中"
        case "HighSchool":
            return "高中"
        case "DaZhuan":
            return "大专"
        case "BenKe":
            return "本科"
        case "ShuoShi":
            return "硕士"
        case "BoShi":
            return "博士"
        case "BoShiHou":
            return "博士后"
        default:
            return ""
        }
        
        
    }
    
    func getCardText(_ type: String) -> String {
        
        switch type {
        case "MonthlyRentCard":
            return "月租卡"
        case "FreeCard":
            return "免费卡"
        default:
            return ""
        }
    }
}

extension CustomerDetailVC: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > UIScreen.navBarHeight {
            if model != nil {
                 title = model.name + "的信息"
            }
        }else{
            title = ""
        }
    }
    
}

